<template>
  <el-dialog
    title="高级查询"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="70%">
    <el-form label-width="80px" ref="dataForm" :model="dataForm" :rules="dataRule">
      <el-row>
        <el-col :span="6">
          <h3>字段选择：</h3>
          <el-form-item label="字段" prop="field">
            <xkl-select-common @change="changeHandle" v-model="dataForm.field" :config="fieldConfig"></xkl-select-common>
          </el-form-item>
          <el-form-item label="规则" prop="regulation">
            <!--<el-input v-model="dataForm.regulation" clearable></el-input>-->
            <xkl-select-common v-model="dataForm.regulation" :config="regulationConfig"></xkl-select-common>
          </el-form-item>
          <el-form-item v-if="dataForm.regulation !== 'is null' && dataForm.regulation !== 'is not null'" label="内容" prop="fieldValue">
            <el-input v-if="!configList.length" v-model="dataForm.fieldValue" placeholder="请输入内容" clearable></el-input>
            <xkl-select-common v-if="dataForm.inputType === 'select' && refreshInput" v-model="dataForm.fieldValue" :config="valueSelectConfig"></xkl-select-common>
            <xkl-date-picker
              v-if="dataForm.inputType === 'date'"
              style="width: 100%"
              v-model="dataForm.fieldValue"
              :type="dataForm.dateType || 'date'" clearable></xkl-date-picker>
          </el-form-item>
          <el-form-item v-if="dataForm.regulation && dataForm.regulation === 'between' && dataForm.inputType !== 'date'" label="" prop="fieldValue">
            <el-input v-model="dataForm.endValue" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14" :offset="1">
          <h3>已选字段：</h3>
          <el-table
            :data="tableData"
            border
            empty-text="暂无查询条件"
            style="width: 100%">
            <el-table-column
              prop="relation"
              label="关系"
              min-width="120"
              width="100"
              align="center">
              <template slot-scope="{row}">
                <span>{{row.relation ? (row.relation === 'and' ? '并且' : '或者') : ''}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="fieldLabel"
              label="字段"
              width="140"
              align="center">
            </el-table-column>
            <el-table-column
              prop="regulationLabel"
              label="规则"
              width="100"
              align="center">
            </el-table-column>
            <el-table-column
              prop="fieldValue"
              label="对应值"
              min-width="200"
              align="center">
              <template slot-scope="{row}">
                <xkl-date-picker
                  v-if="row.inputType === 'date'"
                  style="width: 100%"
                  v-model="row.fieldValue"
                  :type="row.dateType || 'date'" clearable></xkl-date-picker>
                <xkl-select-common v-if="row.inputType === 'select'" v-model="row.fieldValue" :config="row.fieldConfig"></xkl-select-common>
                <template v-if="!row.inputType">
                  <el-input v-model="row.fieldValue" size="mini" clearable></el-input>
                  <el-input style="margin-top: 4px" v-if="row.endValue && row.inputType !== 'date'" v-model="row.endValue" size="mini" clearable></el-input>
                </template>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="80"
              align="center">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.$index, tableData)"
                  type="text"
                  size="small">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
    </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <span>
        <el-button type="success" @click="addSearch('and')">并且</el-button>
        <el-button type="success" @click="addSearch('or')">或者</el-button>
      </span>
      <span>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="queryHandle()">查询</el-button>
        <el-button type="warning" @click="resetForm()">重置</el-button>
      </span>
    </span>
  </el-dialog>
</template>
<script>
  import {toUnderScore} from '../../utils'
  export default {
    components: {},
    props: {
      advancedData: {
        type: Array
      }
    },
    data () {
      return {
        pageIndex: 1,
        pageSize: 10,
        visible: false,
        dataForm: {
          field: '',
          fieldValue: '',
          endValue: '',
          regulation: '',
          inputType: '',
          dateType: ''
        },
        dataRule: {
          field: [{required: true, message: '请输入字段', trigger: 'change'}],
          fieldValue: [{required: true, message: '请输入规则', trigger: 'change'}],
          regulation: [{required: true, message: '请输入内容', trigger: 'blur'}]
        },
        pageId: '',
        tableData: [],
        fieldConfig: {label: '', filterable: true, dataList: [], keyType: 'value', labelType: 'label'},
        regulationConfig: {
          label: '',
          dataList: [
            {label: '等于', value: '='},
            {label: '不等于', value: '!='},
            {label: '大于', value: '>'},
            {label: '大于等于', value: '>='},
            {label: '小于', value: '<'},
            {label: '小于等于', value: '<='},
            // value = "" or value is null
            {label: '为空', value: 'is null'},
            // value != "" or value is not null
            {label: '不为空', value: 'is not null'},
            {label: '包含', value: 'in'},
            {label: '不包含', value: 'not in'},
            {label: '全模糊', value: 'like'},
            {label: '左模糊', value: 'l_like'},
            {label: '右模糊', value: 'r_like'},
            // column between  value1 and value2
            {label: '介于..之间', value: 'between'}
          ],
          keyType: 'value',
          labelType: 'label'
        },
        configList: [],
        valueSelectConfig: {},
        refreshInput: true
      }
    },
    watch: {
      'dataForm.fieldValue' () {
        this.dataForm.endValue = ''
      }
    },
    methods: {
      init () {
        this.visible = true
        this.pageId = this.$route.name
        console.log('this.pageId', this.pageId)
        this.fieldConfig.dataList = this.advancedData.filter(next => next[0] !== 'OPERATION' && (next[2] && next[2].toString().endsWith('senior'))).map(res => {
          return {
            value: res[0],
            label: res[1]
          }
        })
      },
      changeHandle (value) {
        this.dataForm.fieldValue = ''
        this.getDataList(value)
      },
      getDataList (value) {
        this.dataList = []
        this.$http({
          url: this.$http.adornUrl('/proxyKpiApi/sys/sysAdvancedQueryConfig/list'),
          method: 'post',
          data: this.$http.adornData({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'pageId': this.pageId,
            'key': value
          }, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.configList = data.page.list
            if (this.configList.length) {
              this.dataForm.inputType = this.configList[0].type
              this.dataForm.dateType = this.configList[0].dateType
              this.valueSelectConfig = JSON.parse(this.configList[0].config)
              if (this.valueSelectConfig.dataList) {
                this.valueSelectConfig.dataList = JSON.parse(this.valueSelectConfig.dataList)
              }
              this.refreshInput = false
              this.$nextTick(() => {
                this.refreshInput = true
              })
            } else {
              this.valueSelectConfig = {}
              this.dataForm.inputType = ''
              this.dataForm.dateType = ''
            }
          }
        })
      },
      queryHandle () {
        if (this.tableData.length) {
          this.tableData[0].relation = ''
        } else {
          this.$message.warning('请输入查询条件')
          return false
        }
        this.$emit('resetForm')
        let sqlList = this.tableData.map(res => {
          let tmpValue = this.handleSqlVal(res.regulation, res.fieldValue, res.endValue)
          return ' ' + res.relation + ' ' + toUnderScore(res.field) + ' ' + tmpValue
        })
        let sql = sqlList.join('').trim()
        console.log(sql)
        this.$emit('searchData', sql)
      },
      handleSqlVal (regulation, fieldValue, endValue) {
        switch (regulation) {
          case 'in':
          case 'not in':
            return `${regulation}  ('${fieldValue}')`
          case 'between':
            if (Array.isArray(fieldValue)) {
              return `${regulation} ${this.$2formatDate(fieldValue[0], '-')} and  ${this.$2formatDate(fieldValue[1], '-')}`
            }
            return `${regulation} ${fieldValue} and ${endValue}`
          case 'is null':
          case 'is not null':
            return regulation
          case 'like':
            return `%'${fieldValue}'%`
          case 'l_like':
            return `%'${fieldValue}'`
          case 'r_like':
            return `'${fieldValue}'%`
          default:
            return `${regulation} '${fieldValue}'`
        }
      },
      addSearch (type) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let dataForm = {...this.dataForm}
            let fieldConfig = {...this.fieldConfig}
            let regulationConfig = {...this.regulationConfig}
            let valueSelectConfig = {...this.valueSelectConfig}
            let json = {
              relation: this.tableData.length > 0 ? type : '',
              field: dataForm.field,
              fieldLabel: fieldConfig.label,
              regulation: dataForm.regulation,
              regulationLabel: regulationConfig.label,
              fieldValue: dataForm.fieldValue,
              endValue: dataForm.endValue,
              inputType: dataForm.inputType,
              dateType: dataForm.dateType,
              fieldConfig: valueSelectConfig
            }
            this.tableData.push(json)
          }
        })
      },
      deleteRow (index, rows) {
        rows.splice(index, 1)
        if (this.tableData.length) {
          this.tableData[0].relation = ''
        }
      },
      resetForm () {
        this.$resetData(this.dataForm)
        this.$refs.dataForm.resetFields()
        this.tableData = []
        this.configList = []
        this.valueSelectConfig = {}
        this.$emit('resetForm')
      }
    }
  }
</script>
<style lang="less" scoped>
  .dialog-footer{
    display: flex;
    justify-content: space-between;
  }
</style>
